package triangleWorm;

import processing.core.*;

public class MouseMovement implements IWormMovement{
	
	PApplet p;
	float x;
	float y;
	float width;
	float height;
	
	PVector position;
	PVector velocity = new PVector(0, 0, 25f);
	PVector yVelocity = new PVector(0, 0, 25f);
	PVector acceleration = new PVector(0, 0, 0);
	float maxRotation = 0.02f;
	
	public MouseMovement() {
		
	}

	public void init(PApplet processing, PVector worldSize, PVector worldCenter) {
		p = processing;
		
		position = worldCenter;
		
		width = p.width;
		height = p.height;
	}

	public void update() {
		x = p.mouseX;
		y = p.mouseY;

		velocity.add(acceleration);
		//Get current magnitude
		float velocityMagnitude = velocity.mag();
		
		
		//Respond to horizontal movement
		//Calculate mouse x relative to middle of screen
		float halfWidth = width / 2f;
		float xShift = -x + halfWidth;
		//Normalize to the interval -1 to 1
		xShift /= halfWidth;		
		//Calculate rotation
		float yRotation = xShift * maxRotation;
		//Rotate velocity around y axis
		//z' = z*cos q - x*sin q
		//x' = z*sin q + x*cos q
		//y' = y
		float newZ = velocity.z * PApplet.cos(yRotation) - velocity.x * PApplet.sin(yRotation);
		float newX = velocity.z * PApplet.sin(yRotation) + velocity.x * PApplet.cos(yRotation);
		float newY = velocity.y;
		//Set velocity
		velocity.set(newX, newY, newZ);	
		
		//Respond to vertical movement
		//Calculate mouse y relative to middle of screen
		float halfHeight = height / 2f;
		float yShift = y - halfHeight;
		//Normalize
		yShift /= halfHeight;
		float yChange = yShift * 30;
		PVector yMovement = new PVector(0, 1, 0);
		yMovement.mult(yChange);
		//Add vertical movement directly to position... To avoid fucking the velc. vector up
		position.add(yMovement);
		
		
		//Set to current magnitude
		velocity.normalize();
		velocity.mult(velocityMagnitude);
		
		position.add(velocity);		
	}

	public PVector getPosition() {
		return position;
	}

}
